<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t('报告模版') }}</span>
    </div>
    <el-form ref="queryForm" :model="queryParams" :inline="true" @submit.native.prevent>
      <el-form-item :label="$t('报告名称')" prop="reportName">
        <el-input
          v-model="queryParams.reportName"
          :placeholder="$t('报告名称')"
          clearable
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t('搜索') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('重置') }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['market:report:edit']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addHandle"
        >{{ $t('新增') }}</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="marketReportTemplateList" border tooltip-effect="darkTable">
      <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('报告名称')" align="center" prop="reportName" />
      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="300">
        <template slot-scope="scope">
          <!-- <el-button
            v-hasPermi="['market:report:edit']"
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="updateHandle(scope.row)"
          >{{ $t('修改') }}</el-button> -->
          <el-button
            size="small"
            type="text"
            icon="el-icon-download"
            @click="openGenerateReport(scope.row)"
          >{{ $t('生成报告') }}
          </el-button>
          <el-button
            v-hasPermi="['market:report:edit']"
            size="small"
            type="text"
            icon="el-icon-setting"
            @click="openTemplateConfig(scope.row)"
          >{{ $t('模版配置') }}
          </el-button>
          <el-button
            v-hasPermi="['market:report:remove']"
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="deleteHandle(scope.row)"
          >{{ $t('删除') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报告模版对话框 -->
    <el-dialog :title="$t(title)" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <marketReportTemplateForm ref="marketReportTemplateForm" />
    </el-dialog>
    <el-dialog v-el-drag-dialog :title="$t('生成报告')" :visible.sync="reportOpen" width="40%" class="dataForm" :before-close="reportClose" :close-on-click-modal="false" :lock-scroll="false" :destroy-on-close="true">
      <div v-loading="generateLoading">
        <div style="height: 450px;overflow: auto;padding: 20px;margin: -20px;">
          <el-form ref="form" :model="parameterModel" label-width="80px">
            <el-row>
              <div v-for="param in parameterList" :key="param.id">
                <el-col :span="24">
                  <el-form-item :label="$t(param.parameterName)" :rules="[{ required: true, message: '必填信息', trigger: ['blur', 'change'] }]" :prop="param.parameterKey">
                    <div v-if="param.parameterType === 'deal'">
                      <el-select v-model="parameterModel[param.parameterKey]" filterable :placeholder="$t(param.parameterName)" clearable @change="changeParameterValue($event, param)">
                        <el-option
                          v-for="deal in dealOptions"
                          :key="deal.id"
                          :label="$t(deal.dealName)"
                          :value="deal.id"
                        />
                      </el-select>
                    </div>
                    <div v-if="param.parameterType === 'company'">
                      <el-select v-model="parameterModel[param.parameterKey]" filterable :placeholder="$t(param.parameterName)" clearable @change="changeParameterValue($event, param)">
                        <el-option
                          v-for="company in companyOptions"
                          :key="company.id"
                          :label="$t(company.companyName)"
                          :value="company.id"
                        />
                      </el-select>
                    </div>
                    <div v-if="param.parameterType === 'fund'">
                      <el-select v-model="parameterModel[param.parameterKey]" filterable :placeholder="$t(param.parameterName)" clearable @change="changeParameterValue($event, param)">
                        <el-option
                          v-for="fund in fundOptions"
                          :key="fund.id"
                          :label="$t(fund.fundName)"
                          :value="fund.id"
                        />
                      </el-select>
                    </div>
                    <div v-if="param.parameterType === 'date'">
                      <el-date-picker
                        v-model="parameterModel[param.parameterKey]"
                        clearable
                        style="width: 200px"
                        :type="param.parameterFormat ? param.parameterFormat : 'date'"
                        :value-format="param.parameterFormat === 'year' ? 'yyyy' : param.parameterFormat === 'month' ? 'yyyy-MM' : 'yyyy-MM-dd'"
                        :placeholder="$t(param.parameterName)"
                        @change="changeParameterValue($event, param)"
                      />
                    </div>
                    <div v-if="param.parameterType === 'dict'">
                      <dict-select
                        v-model="parameterModel[param.parameterKey]"
                        :dictionary="param.parameterDict"
                        @change="changeParameterValue($event, param)"
                      />
                    </div>
                    <div v-if="param.parameterType === 'text' || param.parameterType === 'other'">
                      <el-input v-model="parameterModel[param.parameterKey]" :placeholder="$t(param.parameterName)" show-word-limit maxlength="50" @change="changeParameterValue($event, param)" />
                    </div>
                  </el-form-item>
                </el-col>
              </div>
            </el-row>
          </el-form>
        </div>

        <div slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button type="primary" @click="generateReport">{{ $t("生成报告") }}</el-button>
          <el-button @click="reportClose">{{ $t("取消") }}</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listMarketReportTemplate, delMarketReportTemplate, exportMarketReportTemplate } from '@/api/market/report/marketReportTemplate'
import marketReportTemplateForm from './marketReportTemplateForm.vue'
import { findFundFof } from '@/api/fund/fundBase'
import { findDeal } from '@/api/base/deal/dealBase'
import { getToken } from '@/utils/auth'
import { config } from '@/utils'
import axios from 'axios'
import { listMarketReportTemplateParameter } from '@/api/market/parameter/marketReportTemplateParameter'
import { findAllCompany } from '@/api/company/base/companyBase'
export default {
    components: {
        marketReportTemplateForm
    },
  data() {
      return {
          // 遮罩层
          loading: true,
          // 总条数
          total: 0,
          // 报告模版表格数据
          marketReportTemplateList: [],
          // 弹出层标题
          title: '报告模版',
          // 是否显示弹出层
          formOpen: false,
          // 查询参数
          queryParams: {
              reportName: undefined,
              fileId: undefined,
              pageNum: 1,
              pageSize: 10
          },
          parameterList: [],
          // 表单参数
          form: {},
          // 表单校验
          rules: {},
          reportOpen: false,
          // 项目options
          dealOptions: [],
          // 标的公司options
          companyOptions: [],
          // 基金options
          fundOptions: [],
          reportParams: {
            queryParameterMapList: []
          },
          generateLoading: false,
          configOpen: false,
          parameterModel: {}
      }
  },
  created() {
      this.getList()
      findDeal(this.dealParams).then(response => {
        this.dealOptions = response.data
      })
      findAllCompany({}).then(response => {
        this.companyOptions = response.rows
      })
      findFundFof().then(response => {
        this.fundOptions = response.data
      })
  },
  methods: {
    /** 查询报告模版列表 */
    getList() {
        this.loading = true
        listMarketReportTemplate(this.queryParams).then(response => {
            this.marketReportTemplateList = response.rows
            this.total = response.total
            this.loading = false
        }).catch(() => {
            this.loading = false
        })
    },
    getParams(id) {
      const queryParams = {}
      queryParams.reportId = id
      listMarketReportTemplateParameter(queryParams).then(response => {
            this.parameterList = response.rows
        }).catch(() => {
            console.log('查询查询参数列表异常')
        })
    },

    // 表单重置
    reset() {
        this.form = {
            id: undefined,
            reportName: undefined,
            fileId: undefined,
            delFlag: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined
        }
        this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
        this.queryParams.pageNum = 1
        this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
        this.resetForm('queryForm')
        this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
        this.formOpen = true
        this.$nextTick(() => {
            this.$refs.marketReportTemplateForm.init(null)
        })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
        this.formOpen = true
        this.$nextTick(() => {
            // 调用form页面的 init 方法初始化数据
            this.$refs.marketReportTemplateForm.init(row)
        })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(() => {
            return delMarketReportTemplate(row.id)
        }).then(() => {
            this.getList()
            this.msgSuccess(this.$t('删除成功'))
        }).catch(() => {
            this.loading = false
        })
    },
    /** 导出按钮操作 */
    exportHandle() {
        const queryParams = this.queryParams
        this.$confirm(this.$t('是否确认导出数据项?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(() => {
            return exportMarketReportTemplate(queryParams)
        }).then(response => {
            this.download(response.msg)
        }).catch(() => {
        })
    },
    openGenerateReport(row) {
      this.reportParams.id = row.id
      this.reportParams.reportName = row.reportName
      this.getParams(row.id)
      this.reportOpen = true
    },
    reportClose() {
      this.reportOpen = false
      this.parameterModel = {}
      this.this.reportParams.queryParameterMapList = []
    },
    generateReport() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          console.log(valid)
          this.generateLoading = true
            console.log(process.env)
            axios({
                  method: 'post',
                  url: config.baseURL + '/report/marketReportTemplate/generateReport',
                  data: this.reportParams,
                  responseType: 'blob',
                  headers: { 'Authorization': 'Bearer ' + getToken() }
                }).then(res => {
                  const blob = res.data
                  const reader = new FileReader()
                  reader.readAsDataURL(blob)
                  reader.onload = (e) => {
                    const a = document.createElement('a')
                    // 获取选择的基金名称
                    a.download = this.reportParams.reportName + '.docx'
                    a.href = e.target.result
                    document.body.appendChild(a)
                    a.click()
                    document.body.removeChild(a)
                    this.generateLoading = false
                  }
                }).catch(error => {
                    console.log(error)
                })
        }
      })
    },
    openTemplateConfig(row) {
      // this.configOpen = true
      this.formOpen = true
        this.$nextTick(() => {
            // 调用form页面的 init 方法初始化数据
            this.$refs.marketReportTemplateForm.init(row)
        })
    },
    configClose() {
      // this.configOpen = false
      this.formOpen = false
    },
    changeParameterValue(val, param) {
      console.log(val)
      console.log(param)
      const queryParam = {}
      queryParam.key = param.parameterKey
      queryParam.value = val
      this.reportParams.queryParameterMapList.push(queryParam)
    }
  }
}
</script>
